//
//  ZYTheHighestScoreController.m
//  BestLearning
//
//  Created by ちょうかんこん on 2017/12/19.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "ZYTheHighestScoreController.h"
#import "ZYTheHighestScoreCell.h"
#import "ZYAllsModel.h"
#define kCell @"cell"
#import "JXAlertview.h"
#import "CustomDayDatePicker.h"
#import "WSDatePickerView.h"
@interface ZYTheHighestScoreController ()<UITableViewDelegate,UITableViewDataSource,CustomAlertDelegete>
{
    NSInteger _mark;//标记类型
    NSString *_selectDate;//标记选中的日期
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong) UIView *allView;
@property (nonatomic,strong) UIView *allTwoView;

@property (nonatomic,strong) UIButton *starButton;
@property (nonatomic,strong) UIButton *endButton;
@property (nonatomic,strong) UILabel *lineLabel;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) CustomDayDatePicker *datePicker;
@end

@implementation ZYTheHighestScoreController

- (NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];


    [self setUpSuperView];
    
    [self setUpRefresh];
}




//- (CustomDayDatePicker *)datePicker {
//
//    if (_datePicker == nil) {
//        self.datePicker = [[CustomDayDatePicker alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth - 60, 140)];
//
//    }
//    return _datePicker;
//}


#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}






- (void)setUpSuperView{
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.estimatedRowHeight = 200;
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[ZYTheHighestScoreCell class] forCellReuseIdentifier:kCell];
    
    self.allView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, 50)];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(0, 0, 50, 50);
    [button setImage:[UIImage imageNamed:@"icon_calendar_default"] forState:(UIControlStateNormal)];
    [self.allView addSubview:button];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 5, kScreenWidth - 60, 40)];
    imageView.image = [UIImage imageNamed:@"bg_xian"];
    [self.allView addSubview:imageView];
    self.tableView.tableHeaderView = self.allView;
    
    
    
    self.lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(imageView.frame.size.width/2 - 5, 19, 10, 2)];
    self.lineLabel.backgroundColor = [UIColor grayColor];
    [imageView addSubview:self.lineLabel];
    
    
    self.starButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.starButton.frame = CGRectMake(imageView.frame.size.width/2 - 145, 0, 140, 40);
    self.starButton.titleLabel.font = [UIFont systemFontOfSize:13];
//    self.starButton.backgroundColor = [UIColor redColor];
//    NSArray *firstStarTimeArray = [[self getTime] componentsSeparatedByString:@" "];
//    NSString *fistTimeStr = [NSString stringWithFormat:@"%@ 00:00",firstStarTimeArray[0]];
    [self.starButton setTitle:[NSString hour] forState:(UIControlStateNormal)];
    [self.starButton setTitleColor:ColorRGB(102, 102, 102) forState:(UIControlStateNormal)];
    imageView.userInteractionEnabled = YES;
    [imageView addSubview:self.starButton];
    
    
    
    
    
    self.endButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.endButton.frame = CGRectMake(self.lineLabel.frame.origin.x + self.lineLabel.frame.size.width, 0, 140, 40);
    self.endButton.titleLabel.font = [UIFont systemFontOfSize:13];
//    self.endButton.backgroundColor = [UIColor greenColor];
    [self.endButton setTitle:[self getTime] forState:(UIControlStateNormal)];
    [self.endButton setTitleColor:ColorRGB(102, 102, 102) forState:(UIControlStateNormal)];
    [imageView addSubview:self.endButton];
    
    
    self.starButton.tag = 201;
    self.endButton.tag = 202;
    
    [self.starButton addTarget:self action:@selector(allButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.endButton addTarget:self action:@selector(allButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
}





- (void)setNetWork{
    
    NSString *url = [NSString stringWithFormat:@"yxhUser.do?action=getExamPaper&lessonId=%@&pageNumber=%ld&startTime=%@&endTime=%@",self.lessonId,(long)self.page,self.starButton.currentTitle,self.endButton.currentTitle];
    
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
 
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        [SVProgressHUD dismiss];
        
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            if (self.isTrue == YES) {
                
                [self.dataSource removeAllObjects];
            }
            
            NSDictionary *t = [Obj valueForKey:@"t"];
            NSArray *arr = [t valueForKey:@"dataList"];
           if (arr != nil && ![arr isKindOfClass:[NSNull class]] && arr.count != 0){
               
               for (NSDictionary *dict in arr) {
                   
                   ZYAllsModel *model = [ZYAllsModel new];
                   
                   [model setValuesForKeysWithDictionary:dict];
                   
                   
                   [self.dataSource addObject:model];
                   
               }
               
               [self.tableView reloadData];
               [self.tableView.mj_header endRefreshing];
               [self.tableView.mj_footer endRefreshing];
               
           }
            
            
            
        }
        
        
        
        
        
    } Fail:^(NSError *Error) {
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
    
    
    
    
    
    
    
    
}




















- (void)allButtonAction:(UIButton *)sender{
    
    NSInteger tag = sender.tag;
    
    
    if (201 == tag) {
        NSDateFormatter *minDateFormater = [[NSDateFormatter alloc] init];
        [minDateFormater setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSDate *scrollToDate = [minDateFormater dateFromString:[self getTime]];
        
        WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinute scrollToDate:scrollToDate CompleteBlock:^(NSDate *selectDate) {
            
            NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd HH:mm"];
            NSLog(@"选择的日期：%@",date);
            [sender setTitle:date forState:UIControlStateNormal];
            
        }];
        datepicker.dateLabelColor = ColorRGB(65, 188, 241);//年-月-日-时-分 颜色
        datepicker.datePickerColor = [UIColor blackColor];//滚轮日期颜色
        datepicker.doneButtonColor = ColorRGB(65, 188, 241);//确定按钮的颜色
        datepicker.yearLabelColor = [UIColor clearColor];//大号年份字体颜色
        [datepicker show];
//        JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 60, 200)];
//        alert.center = self.view.center;
//        alert.delegate = self;
//        [alert initwithtitle:@"开始时间" andcommitbtn:@"确定" andStr:@"0"];
//        [alert addSubview:self.datePicker];
//        [alert show];
//        JGPicker *picker = [[JGPicker alloc] initWithFrame:self.view.frame type:UIDatePickerModeDateAndTime andDelegate:self];
//        picker.delegate = self;
        
        _mark = 1;
        
    }else{
        
//        JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 60, 200)];
//        alert.center = self.view.center;
//        alert.delegate = self;
//        [alert initwithtitle:@"结束时间" andcommitbtn:@"确定" andStr:@"0"];
//        [alert addSubview:self.datePicker];
//        [alert show];
        NSDateFormatter *minDateFormater = [[NSDateFormatter alloc] init];
        [minDateFormater setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSDate *scrollToDate = [minDateFormater dateFromString:[self getTime]];
        
        WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinute scrollToDate:scrollToDate CompleteBlock:^(NSDate *selectDate) {
            
            NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd HH:mm"];
            NSLog(@"选择的日期：%@",date);
           
            [self sureButtonActionWithDate:date WithButton:sender];
        }];
        datepicker.dateLabelColor = ColorRGB(65, 188, 241);//年-月-日-时-分 颜色
        datepicker.datePickerColor = [UIColor blackColor];//滚轮日期颜色
        datepicker.doneButtonColor = ColorRGB(65, 188, 241);//确定按钮的颜色
        datepicker.yearLabelColor = [UIColor clearColor];//大号年份字体颜色
        
        [datepicker show];
       
        
        _mark = 2;
        
    }
    
    
    
    
}





- (void)btnindex:(int)index :(int)tag{
    
    if (index == 2) {
        if (_mark == 1) {
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
            [self.starButton setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
        }else if (_mark == 2){
            
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
            [self.endButton setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
            
            
        }
    }
    
    
    
    
}















#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYTheHighestScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:kCell forIndexPath:indexPath];
    
    if (self.dataSource.count > indexPath.row) {
        
        ZYAllsModel *model = self.dataSource[indexPath.row];
        
        [cell assignByZYAllsModel:model];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    return cell;
}




#pragma mark --- 确定方法的实现
- (void)sureButtonActionWithDate : (NSString *)dateStr WithButton: (UIButton *)sender{
    
    NSString *start = [self.starButton.currentTitle stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *endSelect = [dateStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    
    NSComparisonResult result = [start compare:endSelect];
    
    if (result != NSOrderedAscending) {
        [SVProgressHUD showErrorWithStatus:@"结束时间必须大于开始时间!"];
    }else{
        
        [sender setTitle:dateStr forState:UIControlStateNormal];
        
        [self setSetTowSureStart:self.starButton.currentTitle endSelect:self.endButton.currentTitle];
        
        
        
    }
    
    
    
}




- (void)setSetTowSureStart:(NSString *)startStr endSelect:(NSString *)endSelect{
    
    
    [self.starButton setTitle:startStr forState:(UIControlStateNormal)];
    [self.endButton setTitle:endSelect forState:(UIControlStateNormal)];
    
    
    [self.tableView.mj_header beginRefreshing];
    
    
    
    
    
}



- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [SVProgressHUD dismiss];
    
}

- (NSString *)getTime

{
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    
    NSString *DateTime = [formatter stringFromDate:date];
    
    NSLog(@"%@============年-月-日  时：分：秒=====================",DateTime);
    
    return DateTime;
}





@end
